import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;

public class GetLeastNumbers_Solution {
    // 最小的k个数
    // https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3DSQL%25E7%25AF%2587%26topicId%3D295
    public ArrayList<Integer> GetLeastNumbers_Solution (int[] input, int k) {
        // write code here
        ArrayList<Integer> list = new ArrayList<>();
        if (k == 0) {
            return list;
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> {
            return b-a;
        });
        for (int i = 0; i < input.length; i++) {
            if (queue.size() < k) {
                queue.offer(input[i]);
            } else {
                if (input[i] < queue.peek()) {
                    queue.poll();
                    queue.offer(input[i]);
                }
            }
        }
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            list.add(queue.poll());
        }
        return list;
    }

    public static void main(String[] args) {
        int[] input = new int[]{4,5,1,6,2,7,3,8};
        GetLeastNumbers_Solution solution = new GetLeastNumbers_Solution();
        System.out.println(solution.GetLeastNumbers_Solution(input, 4));
    }
}
